package org.sith.taskrunner.gwt.client.presenter;


import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.HasWidgets;
import org.sith.taskrunner.gwt.client.dataloader.ExecutionStateWatcher;
import org.sith.taskrunner.gwt.client.dataloader.LoadInitDataStateHolder;
import org.sith.taskrunner.gwt.client.event.DataLoadEvent;
import org.sith.taskrunner.gwt.client.event.DataLoadEventHandler;
import org.sith.taskrunner.gwt.client.event.LoadInitDataEvent;
import org.sith.taskrunner.gwt.client.view.IDataLoadView;

public class DataLoadPresenter implements DataLoadEventHandler, Presenter {


    private IDataLoadView view;
    private LoadInitDataStateHolder stateHolder;
    private EventBus eventBus;

    public DataLoadPresenter(IDataLoadView view, LoadInitDataStateHolder stateHolder, final EventBus eventBus) {
        this.view = view;
        this.stateHolder = stateHolder;
        this.eventBus = eventBus;


        stateHolder.setExecutionStateWatcher(new ExecutionStateWatcher() {
            @Override
            public void executionState(String message, boolean successfully, boolean hasNext) {
                DataLoadEvent event = new DataLoadEvent(message, successfully, hasNext);
                eventBus.fireEvent(event);
            }
        });


        bind();


    }

    private void bind() {
        eventBus.addHandler(DataLoadEvent.TYPE, this);
    }


    @Override
    public void onDataLoaded(DataLoadEvent value) {

        view.addLogLine(value.getMessage(), value.isSuccessfully());

        if (value.isSuccessfully() && value.isHasNext()) {
            stateHolder.nextElement();
        } else if (!value.isSuccessfully()) {
            view.showCloseButton();
        } else if (!value.isHasNext()) {
            view.close();
            eventBus.fireEvent(new LoadInitDataEvent());
            //TODO fire event that initial data is loaded

        }


    }

    @Override
    public void go(HasWidgets container) {
        view.show();
        stateHolder.startLoad();
    }
}